/* eslint-disable */
/*
 * @Descripttion: 微信支付
 * @version: 1.0.0
 * @Author: shuaishuai.han
 * @Date: 2022-01-13 08:51:55
 */
import { Notify } from 'vant';

export const weixinPay = (params) => {
  if (typeof WeixinJSBridge == 'undefined') {
    if (document.addEventListener) {
      document.addEventListener(
        'WeixinJSBridgeReady',
        onBridgeReady(params),
        false
      );
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady(params));
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(params));
    }
  } else {
    return new Promise((resolve, reject) => {
      onBridgeReady(params).then((res) => {
        if (res === 'SUCCESS' || res === 'CLOSED') {
          resolve(res);
        } else {
          reject('FAIL');
        }
      });
    });
  }
};

const onBridgeReady = (params) => {
  return new Promise((resolve, reject) => {
    try {
      const { appId, timeStamp, nonceStr, packageExt, signType, paySign } =
        params;
      const dpTimestamp = Math.round(timeStamp).toString();
      let wxParams = {
        appId, //公众号名称，由商户传入
        timeStamp: dpTimestamp, //时间戳，自1970年以来的秒数
        nonceStr, //随机串
        package: packageExt,
        signType: signType, //微信签名方式：
        paySign: paySign //微信签名
      };
      window.WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        wxParams,
        function (res) {
          removeEvent();
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == 'get_brand_wcpay_request:ok') {
            // 支付成功后的操作
            // 稍后进入订单管理页核实订单状态，不要重复发起支付
            resolve('SUCCESS');
            // 调用后端接口
          } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
            //取消支付的操作
            resolve('CLOSED');
          } else {
            //支付失败的操作
            resolve('FAIL');
          }
        }
      );
    } catch (error) {
      Notify(error.message || '请求接口失败');
    }
  });
};

// 清除监听
const removeEvent = () => {
  if (document.addEventListener) {
    document.removeEventListener('WeixinJSBridgeReady', onBridgeReady, false);
  } else if (document.attachEvent) {
    document.detachEvent('WeixinJSBridgeReady', onBridgeReady);
    document.detachEvent('onWeixinJSBridgeReady', onBridgeReady);
  }
};
